package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.Visitor;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class VisitorsApiImpl implements VisitorsApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public List<Visitor> visitors(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(5);
        List<Visitor> visitors = mongoTemplate.find(query, Visitor.class);
        return visitors;
    }

    @Override
    public List<Visitor> secvisitors(Long userId, long time) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("created").gt(time));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(5);
        List<Visitor> visitors = mongoTemplate.find(query, Visitor.class);
        return visitors;
    }

    @Override
    public PageResult findVisitors(Long userId, Integer page, Integer pagesize) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("date")));
        query.with(PageRequest.of(page-1,pagesize));
        List<Visitor> visitors = mongoTemplate.find(query, Visitor.class);
        long count = mongoTemplate.count(query, Visitor.class);
        int pages = (int) Math.ceil(count*1.0/pagesize);

        return new PageResult((int) count,pagesize,pages,page,visitors);
    }
}
